class User < ActiveRecord::Base
  ROLES = ['user', 'admin']

  acts_as_paranoid
  
  validates_presence_of     :username, :password, :firstname, :lastname, :email
  validates_uniqueness_of   :username
  validates_length_of       :password, :minimum => 6
  validates_confirmation_of :password
  validates_inclusion_of    :role, :in => ROLES
  
  attr_accessor :password_confirmation

  has_many :accounts
  has_many :payable_bills
  has_many :bills

  
  def is_user?
    role == 'user'
  end
  
  def is_admin?
    role == 'admin'
  end
  
  def name
    "#{self.firstname} #{self.lastname}"
  end
  
  def hashed_password
    Digest::SHA256.hexdigest("#{created_at}-#{username}-#{password}")
  end
  
  def self.authenticate(username, password)
    find(:first, :conditions => [ "username = ? AND password = ?", username, password ])
  end
  
  def self.authenticate_hashed(username, hashed_password)
    user = find(:first, :conditions => [ "username = ?", username ])
    pass = Digest::SHA256.hexdigest("#{user.created_at}-#{user.username}-#{user.password}")
    
    if pass == hashed_password
      user
    else
      nil
    end
  end

  def find_unpaid_bills
    payable_bills.find(:all, :conditions => "paid_at IS NULL").sort { |x,y| x.due <=> y.due }
  end
  
  def find_unseen_unpaid_bills
    payable_bills.find(:all, :conditions => "paid_at IS NULL AND seen=0").sort { |x,y| x.due <=> y.due }
  end
end
